package org.snusmumr.android.media.data;

import org.snusmumr.android.media.util.Utils;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import android.provider.Contacts.People;

@SuppressWarnings("deprecation")
public class ContactAPISdk3 extends ContactAPI {
	private static final IContactMetaData META_DATA = new MetaDataSdk3();
	
	@Override
	public Intent getContactIntent() {
		return(new Intent(Intent.ACTION_PICK, People.CONTENT_URI));
	}
	
	@Override
	public IContactMetaData getMetaData() {
		return META_DATA;
	}
	
	@Override
	public Cursor getContactsCursor(String selection, String[] selectionArgs, String sortOrder) {
		if(Utils.isEmpty(selection))
			selection = META_DATA.displayName() + " is not null";
		else
			selection += " and " + META_DATA.displayName() + " is not null";
		Cursor cur = getContentResolver().query(People.CONTENT_URI, 
			getBasicContactProjection(), selection, selectionArgs, sortOrder);
		return cur;
	}
	
	public long insertContact(String name) {
		ContentValues personValues = new ContentValues();
		personValues.put(Contacts.People.NAME, name);
		/* STARRED 0 = Contacts, 1 = Favorites */
		personValues.put(Contacts.People.STARRED, 0);

		Uri newPersonUri = Contacts.People
		  .createPersonInMyContactsGroup(getContentResolver(), personValues);
		
		return ContentUris.parseId(newPersonUri);
	}
	
	/**
	 * Android 1.6 implementation of IContactMetaData
	 * @author Denis Kruglyakov
	 *
	 */
	private final static class MetaDataSdk3 implements IContactMetaData {

		@Override
		public String id() {
			return People._ID;
		}

		@Override
		public String displayName() {
			return People.DISPLAY_NAME;
		}
		
		@Override
		public Uri getUri() {
			return People.CONTENT_URI;
		}
		
	}

}
